package com.jfeat.am.module.wegou.api.shop.crud;

import com.baomidou.mybatisplus.plugins.Page;
import com.jfeat.am.common.constant.tips.ErrorTip;
import com.jfeat.am.common.constant.tips.SuccessTip;
import com.jfeat.am.common.constant.tips.Tip;
import com.jfeat.am.common.controller.BaseController;
import com.jfeat.am.common.exception.BusinessException;
import com.jfeat.am.module.wegou.annotation.UserIdentity;
import com.jfeat.am.module.wegou.constant.Identify;
import com.jfeat.am.module.wegou.exception.WegouBizException;
import com.jfeat.am.module.wegou.services.crud.service.ProductTypeService;
import com.jfeat.am.module.wegou.services.domain.service.QueryProductTypeService;
import com.jfeat.am.module.wegou.services.patch.ProductTypePatchService;
import com.jfeat.am.module.wegou.services.persistence.model.ProductStore;
import com.jfeat.am.module.wegou.services.persistence.model.ProductType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * <p>
 * 产品类别表 api
 * </p>
 *
 * @author Code Generator
 * @since 2018-01-03
 */
@Api("料理类型（料理店铺使用）")
@RestController
@RequestMapping("/api/shop/product/type")
public class ProductTypeEndpointForShop extends BaseController {

    @Resource
    ProductTypeService productTypeService;

    @Resource
    QueryProductTypeService queryProductTypeService;

    @Resource
    ProductTypePatchService productTypePatchService;

    @ApiOperation(value = "料理类型 新建料理类型", response = ProductType.class)
    @PostMapping
    @UserIdentity("STORE")
    public Tip createProductType(@RequestBody ProductType entity) {
        ProductStore productRestaurant = getAttr("productStore");
        entity.setStoreId(productRestaurant.getId());

        //校验正在添加的料理类型的“中文名和日文名”不能和本店铺的已有料理类型的重复
        try {
            productTypePatchService.isProductTypeNameDuplicated(productRestaurant.getId(), entity, false);
        } catch (BusinessException e) {
            return ErrorTip.create(e.getCode(), e.getMessage());
        }
        productTypeService.createGroup(entity);
        return SuccessTip.create(entity);
    }

    @ApiOperation(value = "料理类型 查看料理类型", response = ProductType.class)
    @GetMapping("/{id}")
    @UserIdentity("STORE")
    public Tip getProductType(@PathVariable Long id) {
        return SuccessTip.create(productTypeService.retrieveGroup(id));
    }

    @ApiOperation(value = "料理类型 修改料理类型", response = ProductType.class)
    @PutMapping("/{id}")
    @UserIdentity("STORE")
    public Tip updateProductType(@PathVariable Long id, @RequestBody ProductType entity) {
        ProductStore productRestaurant = getAttr("productStore");
        //检查必须是自己店铺的子类别才允许更新
        ProductType originEntity = productTypeService.retrieveGroup(id);
        if (!originEntity.getStoreId().equals(productRestaurant.getId())) {
            return ErrorTip.create(WegouBizException.NOT_YOUR_PRODUCT_TYPE.getCode(),
                    WegouBizException.NOT_YOUR_PRODUCT_TYPE.getMessage());
        }

        //不能作为自己的子类别
        if (originEntity.getId().equals(entity.getPid())) {
            return ErrorTip.create(WegouBizException.CATEGORY_CANNOT_BE_HIS_OWN_CHILD.getCode(),
                    WegouBizException.CATEGORY_CANNOT_BE_HIS_OWN_CHILD.getMessage());
        }

        //校验正在更新的料理类型的“中文名和日文名”不能和本店铺的已有料理类型的重复
        try {
            productTypePatchService.isProductTypeNameDuplicated(productRestaurant.getId(), entity, true);
        } catch (BusinessException e) {
            return ErrorTip.create(e.getCode(), e.getMessage());
        }

        entity.setId(id);
        productTypeService.updateGroup(entity);
        return SuccessTip.create(entity);
    }

    @ApiOperation(value = "料理类型 删除某个料理类型", response = ProductType.class)
    @DeleteMapping("/{id}")
    @UserIdentity("STORE")
    public Tip deleteProductType(@PathVariable Long id) {
        if (productTypePatchService.hasChildren(id)) {
            return ErrorTip.create(WegouBizException.CANNOT_DELETE_WITH_CHILDREN.getCode(),
                    WegouBizException.CANNOT_DELETE_WITH_CHILDREN.getMessage());
        }
        if (productTypePatchService.refBySomeProducts(id)) {
            return ErrorTip.create(WegouBizException.CANNOT_DELETE_REF_SOME_PRODUCTS.getCode(),
                    WegouBizException.CANNOT_DELETE_REF_SOME_PRODUCTS.getMessage());
        }
        return SuccessTip.create(productTypeService.deleteGroup(id));
    }

    @ApiOperation(value = "料理类型 查询料理类型（分页）", response = ProductType.class)
    @GetMapping
    @UserIdentity("STORE")
    public Tip queryProductTypes(Page page,
                                 @RequestParam(name = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                 @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                 @RequestParam(name = "id", required = false) Long id,
                                 @RequestParam(name = "typeName", required = false) String typeName,
                                 @RequestParam(name = "zhTypeName", required = false) String zhTypeName,
                                 @RequestParam(name = "sortNumber", required = false) Integer sortNumber) {
        ProductStore productRestaurant = getAttr(Identify.PRODUCT_STORE);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        ProductType productType = new ProductType();
        productType.setId(id);
        productType.setTypeName(typeName);
        productType.setZhTypeName(zhTypeName);
        productType.setSortNumber(sortNumber);
        productType.setStoreId(productRestaurant.getId());

        page.setRecords(queryProductTypeService.recurisivelyFindProductTypesPage(page, productType));
        return SuccessTip.create(page);
    }

    @ApiOperation(value = "料理类型 查询料理类型（不分页）", response = ProductType.class)
    @GetMapping("/all")
    @UserIdentity("STORE")
    public Tip queryAllProductTypes() {
        ProductStore productRestaurant = getAttr(Identify.PRODUCT_STORE);
        return SuccessTip.create(queryProductTypeService.recurisivelyFindAllProductTypes(productRestaurant.getId()));
    }
}
